#!/bin/bash

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"

if [[ "$PROJECT_ROOT" =~ ^/([a-zA-Z])/(.*) ]]; then
  DRIVE_LETTER="${BASH_REMATCH[1]}"
  PATH_REMAINDER="${BASH_REMATCH[2]}"
  PROJECT_ROOT="${DRIVE_LETTER^^}:/${PATH_REMAINDER}"
fi

ACORE_JSON_PATH="$PROJECT_ROOT/acore.json"
DB_WORLD_UPDATE_DIR="$PROJECT_ROOT/data/sql/updates/db_world"

VERSION_LINE=$(grep '"version"' "$ACORE_JSON_PATH")
VERSION=$(echo "$VERSION_LINE" | sed -E 's/.*"version": *"([^"]+)".*/\1/')

# Parse version into parts
if [[ "$VERSION" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)(.*)$ ]]; then
  MAJOR="${BASH_REMATCH[1]}"
  SUFFIX="${BASH_REMATCH[4]}"
  NEW_VERSION="$((MAJOR + 1)).0.0$SUFFIX"

  # Replace version in file
  sed -i.bak -E "s/(\"version\": *\")[^\"]+(\" *)/\1$NEW_VERSION\2/" "$ACORE_JSON_PATH"
  rm -f "$ACORE_JSON_PATH.bak"

  echo "✅ Version updated to $NEW_VERSION"
else
  echo "Error: Could not parse version string: $VERSION"
  exit 1
fi

# Extract the new major version from NEW_VERSION
if [[ "$NEW_VERSION" =~ ^([0-9]+)\. ]]; then
  NEW_MAJOR="${BASH_REMATCH[1]}"
else
  echo "Error: Unable to extract major version from $NEW_VERSION"
  exit 1
fi

# Prepare SQL content
DB_VERSION_CONTENT="'ACDB 335.${NEW_MAJOR}-dev'"
SQL_QUERY="UPDATE \`version\` SET \`db_version\`=${DB_VERSION_CONTENT}, \`cache_id\`=${NEW_MAJOR} LIMIT 1;"

# Format date as yyyy_mm_dd
TODAY=$(date +%Y_%m_%d)

# Ensure directory exists
mkdir -p "$DB_WORLD_UPDATE_DIR"

# List existing files for today
existing_files=($(find "$DB_WORLD_UPDATE_DIR" -maxdepth 1 -type f -name "${TODAY}_*.sql" 2>/dev/null))

# Determine next xx counter
# Determine next xx
COUNTER="00"
if [ ${#existing_files[@]} -gt 0 ]; then
  max=0
  for file in "${existing_files[@]}"; do
    basename=$(basename "$file")
    if [[ "$basename" =~ ^${TODAY}_([0-9]{2})\.sql$ ]]; then
      num=${BASH_REMATCH[1]}
      if [[ "$num" =~ ^[0-9]+$ ]] && (( 10#$num > max )); then
        max=$((10#$num))
      fi
    fi
  done
  COUNTER=$(printf "%02d" $((max + 1)))
fi

# Compose final file path
SQL_FILENAME="${TODAY}_${COUNTER}.sql"
SQL_FILE_PATH="$DB_WORLD_UPDATE_DIR/$SQL_FILENAME"

# Write to file
{
  echo "-- Auto-generated by VersionUpdater.sh on $(date)"
  echo "$SQL_QUERY" 
} > "$SQL_FILE_PATH"

echo "✅ SQL file created at $SQL_FILE_PATH"
